<template>
  <div class="drawing-test-page">
    <div class="page-header">
      <h1>绘图功能测试</h1>
      <p>测试本地Canvas绘图功能，包括画笔、橡皮擦、颜色选择等</p>
    </div>
    
    <!-- 添加SignalR连接测试 -->
    <div class="connection-test">
      <h3>SignalR连接测试</h3>
      <div class="connection-status">
        <span>连接状态: </span>
        <span :class="{ connected: isConnected }">{{ isConnected ? '已连接' : '未连接' }}</span>
      </div>
      <div class="connection-actions">
        <el-button @click="connectSignalR" :disabled="isConnected" type="primary">
          连接SignalR
        </el-button>
        <el-button @click="disconnectSignalR" :disabled="!isConnected" type="danger">
          断开连接
        </el-button>
        <el-button @click="testPaintAction" :disabled="!isConnected" type="success">
          测试涂色动作
        </el-button>
      </div>
    </div>
    
    <div class="main-content">
      <!-- 左侧工具栏 -->
      <div class="left-panel">
        <DrawingToolbar
          v-model="toolState"
          :can-undo="canUndo"
          :can-redo="canRedo"
          @tool-change="onToolChange"
          @undo="undo"
          @redo="redo"
          @clear="clearCanvas"
          @add-layer="addLayer"
          @toggle-layer="toggleLayer"
        />
      </div>
      
      <!-- 中间画布区域 -->
      <div class="center-panel">
        <div class="canvas-container">
          <canvas
            ref="canvasRef"
            :width="canvasWidth"
            :height="canvasHeight"
            class="test-canvas"
            @mousedown="startDrawing"
            @mousemove="draw"
            @mouseup="stopDrawing"
            @mouseleave="stopDrawing"
            @touchstart="handleTouchStart"
            @touchmove="handleTouchMove"
            @touchend="handleTouchEnd"
          ></canvas>
          
          <!-- 画布信息 -->
          <div class="canvas-info">
            <div class="info-item">
              <span>工具:</span>
              <span class="value">{{ getToolLabel(toolState.tool) }}</span>
            </div>
            <div class="info-item">
              <span>大小:</span>
              <span class="value">{{ toolState.size }}px</span>
            </div>
            <div class="info-item">
              <span>颜色:</span>
              <div class="color-preview" :style="{ backgroundColor: toolState.color }"></div>
            </div>
            <div class="info-item">
              <span>透明度:</span>
              <span class="value">{{ toolState.opacity }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧控制面板 -->
      <div class="right-panel">
        <div class="control-panel">
          <h3>控制面板</h3>
          
          <!-- 画布设置 -->
          <div class="control-section">
            <h4>画布设置</h4>
            <div class="setting-item">
              <label>画布大小:</label>
              <el-select v-model="canvasSize" @change="resizeCanvas" size="small">
                <el-option label="400x300" value="400x300" />
                <el-option label="800x600" value="800x600" />
                <el-option label="1024x768" value="1024x768" />
                <el-option label="1920x1080" value="1920x1080" />
              </el-select>
            </div>
            
            <div class="setting-item">
              <label>背景颜色:</label>
              <el-color-picker v-model="backgroundColor" @change="changeBackground" size="small" />
            </div>
          </div>
          
          <!-- 历史记录 -->
          <div class="control-section">
            <h4>历史记录</h4>
            <div class="history-info">
              <p>操作次数: {{ actionHistory.length }}</p>
              <p>可撤销: {{ canUndo ? '是' : '否' }}</p>
              <p>可重做: {{ canRedo ? '是' : '否' }}</p>
            </div>
            
            <div class="history-actions">
              <el-button @click="clearHistory" type="danger" size="small" :disabled="actionHistory.length === 0">
                清空历史
              </el-button>
            </div>
          </div>
          
          <!-- 导出功能 -->
          <div class="control-section">
            <h4>导出功能</h4>
            <div class="export-actions">
              <el-button @click="exportAsPNG" type="success" size="small">
                导出PNG
              </el-button>
              <el-button @click="exportAsJPEG" type="warning" size="small">
                导出JPEG
              </el-button>
            </div>
          </div>
          
          <!-- 测试功能 -->
          <div class="control-section">
            <h4>测试功能</h4>
            <div class="test-actions">
              <el-button @click="testBrush" type="primary" size="small">
                测试画笔
              </el-button>
              <el-button @click="testEraser" type="info" size="small">
                测试橡皮擦
              </el-button>
              <el-button @click="testFill" type="success" size="small">
                测试填充
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 底部状态栏 -->
    <div class="status-bar">
      <div class="status-item">
        <span>鼠标位置:</span>
        <span class="value">{{ mousePosition.x }}, {{ mousePosition.y }}</span>
      </div>
      <div class="status-item">
        <span>绘制状态:</span>
        <span class="value">{{ isDrawing ? '绘制中' : '空闲' }}</span>
      </div>
      <div class="status-item">
        <span>FPS:</span>
        <span class="value">{{ fps }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import DrawingToolbar from '@/components/DrawingToolbar.vue'
import { createSignalRService } from '@/services/socketService'
import { useGameStore } from '@/stores/game'

// 画布相关
const canvasRef = ref(null)
const canvasWidth = ref(800)
const canvasHeight = ref(600)
const ctx = ref(null)
const isDrawing = ref(false)
const lastX = ref(0)
const lastY = ref(0)

// 工具状态
const toolState = ref({
  tool: 'brush',
  size: 10,
  color: '#1890ff',
  opacity: 1
})

// 画布设置
const canvasSize = ref('800x600')
const backgroundColor = ref('#ffffff')

// 历史记录
const actionHistory = ref([])
const redoHistory = ref([])
const maxHistorySize = 100

// SignalR相关
const gameStore = useGameStore()
const signalRService = createSignalRService(gameStore)
const isConnected = ref(false)

// 鼠标位置和FPS
const mousePosition = ref({ x: 0, y: 0 })
const fps = ref(0)
let frameCount = 0
let lastTime = Date.now()

// 计算属性
const canUndo = computed(() => actionHistory.value.length > 0)
const canRedo = computed(() => redoHistory.value.length > 0)

onMounted(() => {
  initCanvas()
  startFPSCounter()
  setupSignalR()
})

onUnmounted(() => {
  stopFPSCounter()
  cleanupSignalR()
})

function initCanvas() {
  const canvas = canvasRef.value
  if (!canvas) return

  ctx.value = canvas.getContext('2d')
  
  // 设置画布背景
  ctx.value.fillStyle = backgroundColor.value
  ctx.value.fillRect(0, 0, canvasWidth.value, canvasHeight.value)
  
  // 设置画笔样式
  updateBrushStyle()
}

function updateBrushStyle() {
  if (!ctx.value) return
  
  if (toolState.value.tool === 'brush') {
    ctx.value.strokeStyle = toolState.value.color
    ctx.value.fillStyle = toolState.value.color
  } else if (toolState.value.tool === 'eraser') {
    ctx.value.strokeStyle = backgroundColor.value
    ctx.value.fillStyle = backgroundColor.value
  }
  
  ctx.value.lineWidth = toolState.value.size
  ctx.value.lineCap = 'round'
  ctx.value.lineJoin = 'round'
}

function onToolChange(newToolState) {
  toolState.value = newToolState
  updateBrushStyle()
}

function startDrawing(event) {
  isDrawing.value = true
  const rect = canvasRef.value.getBoundingClientRect()
  lastX.value = event.clientX - rect.left
  lastY.value = event.clientY - rect.top
  
  updateBrushStyle()
  recordAction('start', lastX.value, lastY.value)
}

function draw(event) {
  if (!isDrawing.value) return
  
  const rect = canvasRef.value.getBoundingClientRect()
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top
  
  // 更新鼠标位置
  mousePosition.value = { x: Math.round(x), y: Math.round(y) }
  
  // 根据工具类型绘制
  if (toolState.value.tool === 'brush') {
    drawBrush(x, y)
  } else if (toolState.value.tool === 'eraser') {
    drawEraser(x, y)
  } else if (toolState.value.tool === 'fill') {
    fillArea(x, y)
  }
  
  lastX.value = x
  lastY.value = y
}

function drawBrush(x, y) {
  if (!ctx.value) return
  
  ctx.value.beginPath()
  ctx.value.moveTo(lastX.value, lastY.value)
  ctx.value.lineTo(x, y)
  ctx.value.stroke()
  
  recordAction('draw', x, y)
}

function drawEraser(x, y) {
  if (!ctx.value) return
  
  ctx.value.beginPath()
  ctx.value.arc(x, y, toolState.value.size / 2, 0, 2 * Math.PI)
  ctx.value.fill()
  
  recordAction('erase', x, y)
}

function fillArea(x, y) {
  if (!ctx.value) return
  
  // 简单的填充算法（简化版）
  const imageData = ctx.value.getImageData(0, 0, canvasWidth.value, canvasHeight.value)
  const targetColor = getPixelColor(imageData, x, y)
  
  if (targetColor !== toolState.value.color) {
    floodFill(imageData, x, y, targetColor, toolState.value.color)
    ctx.value.putImageData(imageData, 0, 0)
    recordAction('fill', x, y)
  }
}

function getPixelColor(imageData, x, y) {
  const index = (y * imageData.width + x) * 4
  return `rgb(${imageData.data[index]}, ${imageData.data[index + 1]}, ${imageData.data[index + 2]})`
}

function floodFill(imageData, x, y, targetColor, replacementColor) {
  // 简化的填充算法
  const stack = [{ x, y }]
  const targetRGB = parseRGB(targetColor)
  const replacementRGB = parseRGB(replacementColor)
  
  while (stack.length > 0) {
    const { x: currentX, y: currentY } = stack.pop()
    
    if (currentX < 0 || currentX >= imageData.width || 
        currentY < 0 || currentY >= imageData.height) {
      continue
    }
    
    const index = (currentY * imageData.width + currentX) * 4
    const currentRGB = {
      r: imageData.data[index],
      g: imageData.data[index + 1],
      b: imageData.data[index + 2]
    }
    
    if (currentRGB.r === targetRGB.r && 
        currentRGB.g === targetRGB.g && 
        currentRGB.b === targetRGB.b) {
      
      imageData.data[index] = replacementRGB.r
      imageData.data[index + 1] = replacementRGB.g
      imageData.data[index + 2] = replacementRGB.b
      
      stack.push({ x: currentX + 1, y: currentY })
      stack.push({ x: currentX - 1, y: currentY })
      stack.push({ x: currentX, y: currentY + 1 })
      stack.push({ x: currentX, y: currentY - 1 })
    }
  }
}

function parseRGB(rgbString) {
  const match = rgbString.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/)
  if (match) {
    return {
      r: parseInt(match[1]),
      g: parseInt(match[2]),
      b: parseInt(match[3])
    }
  }
  return { r: 0, g: 0, b: 0 }
}

function stopDrawing() {
  isDrawing.value = false
}

function recordAction(type, x, y) {
  const action = {
    type,
    x: Math.round(x),
    y: Math.round(y),
    tool: toolState.value.tool,
    size: toolState.value.size,
    color: toolState.value.color,
    timestamp: Date.now()
  }
  
  actionHistory.value.push(action)
  redoHistory.value = [] // 清空重做历史
  
  if (actionHistory.value.length > maxHistorySize) {
    actionHistory.value.shift()
  }
}

function undo() {
  if (actionHistory.value.length === 0) return
  
  const lastAction = actionHistory.value.pop()
  redoHistory.value.push(lastAction)
  
  // 重新绘制画布（简化版本）
  redrawCanvas()
}

function redo() {
  if (redoHistory.value.length === 0) return
  
  const action = redoHistory.value.pop()
  actionHistory.value.push(action)
  
  // 重新绘制画布
  redrawCanvas()
}

function redrawCanvas() {
  // 清空画布
  ctx.value.fillStyle = backgroundColor.value
  ctx.value.fillRect(0, 0, canvasWidth.value, canvasHeight.value)
  
  // 重新绘制所有动作
  actionHistory.value.forEach(action => {
    if (action.type === 'draw') {
      ctx.value.strokeStyle = action.color
      ctx.value.lineWidth = action.size
      ctx.value.beginPath()
      ctx.value.arc(action.x, action.y, action.size / 2, 0, 2 * Math.PI)
      ctx.value.fill()
    }
  })
}

function clearCanvas() {
  if (!ctx.value) return
  
  ctx.value.fillStyle = backgroundColor.value
  ctx.value.fillRect(0, 0, canvasWidth.value, canvasHeight.value)
  
  recordAction('clear', 0, 0)
}

function clearHistory() {
  actionHistory.value = []
  redoHistory.value = []
}

function resizeCanvas() {
  const [width, height] = canvasSize.value.split('x').map(Number)
  canvasWidth.value = width
  canvasHeight.value = height
  
  // 重新初始化画布
  initCanvas()
}

function changeBackground() {
  backgroundColor.value = backgroundColor.value
  initCanvas()
}

function addLayer() {
  // 图层功能（简化版本）
  console.log('添加新图层')
}

function toggleLayer() {
  // 切换图层可见性（简化版本）
  console.log('切换图层可见性')
}

// 触摸事件处理
function handleTouchStart(event) {
  event.preventDefault()
  const touch = event.touches[0]
  const rect = canvasRef.value.getBoundingClientRect()
  lastX.value = touch.clientX - rect.left
  lastY.value = touch.clientY - rect.top
  
  isDrawing.value = true
  updateBrushStyle()
  recordAction('start', lastX.value, lastY.value)
}

function handleTouchMove(event) {
  event.preventDefault()
  if (!isDrawing.value) return
  
  const touch = event.touches[0]
  const rect = canvasRef.value.getBoundingClientRect()
  const x = touch.clientX - rect.left
  const y = touch.clientY - rect.top
  
  if (toolState.value.tool === 'brush') {
    drawBrush(x, y)
  } else if (toolState.value.tool === 'eraser') {
    drawEraser(x, y)
  }
  
  lastX.value = x
  lastY.value = y
}

function handleTouchEnd(event) {
  event.preventDefault()
  isDrawing.value = false
}

// 测试功能
function testBrush() {
  toolState.value.tool = 'brush'
  toolState.value.size = 20
  toolState.value.color = '#ff0000'
  updateBrushStyle()
}

function testEraser() {
  toolState.value.tool = 'eraser'
  toolState.value.size = 30
  updateBrushStyle()
}

function testFill() {
  toolState.value.tool = 'fill'
  toolState.value.color = '#00ff00'
  updateBrushStyle()
}

// 工具标签
function getToolLabel(tool) {
  const labels = {
    brush: '画笔',
    eraser: '橡皮擦',
    fill: '填充',
    eyedropper: '吸管'
  }
  return labels[tool] || tool
}

// SignalR相关方法
function setupSignalR() {
  console.log('设置SignalR连接...')
  
  // 监听连接状态变化
  signalRService.on('Connected', () => {
    console.log('SignalR已连接')
    isConnected.value = true
  })
  
  signalRService.on('Disconnected', () => {
    console.log('SignalR已断开')
    isConnected.value = false
  })
  
  signalRService.on('PaintActionReceived', (paintData) => {
    console.log('收到涂色动作:', paintData)
    // 在测试页面中，我们可以显示收到的涂色动作
  })
}

function cleanupSignalR() {
  console.log('清理SignalR连接...')
  signalRService.off('Connected')
  signalRService.off('Disconnected')
  signalRService.off('PaintActionReceived')
}

function connectSignalR() {
  console.log('连接SignalR...')
  signalRService.connect()
}

function disconnectSignalR() {
  console.log('断开SignalR连接...')
  signalRService.disconnect()
}

function testPaintAction() {
  console.log('测试涂色动作...')
  
  // 发送一个测试涂色动作
  const testData = {
    x: Math.floor(Math.random() * 800),
    y: Math.floor(Math.random() * 600),
    color: '#' + Math.floor(Math.random()*16777215).toString(16),
    brushSize: Math.floor(Math.random() * 20) + 5,
    tool: 'brush'
  }
  
  signalRService.sendPaintAction(
    'test-room',
    'test-player',
    testData.x,
    testData.y,
    testData.color,
    testData.brushSize,
    testData.tool
  )
  
  console.log('测试涂色动作已发送:', testData)
}

// FPS计数器
function startFPSCounter() {
  const countFPS = () => {
    frameCount++
    const currentTime = Date.now()
    
    if (currentTime - lastTime >= 1000) {
      fps.value = frameCount
      frameCount = 0
      lastTime = currentTime
    }
    
    requestAnimationFrame(countFPS)
  }
  
  countFPS()
}

function stopFPSCounter() {
  // 清理FPS计数器
}

// 导出功能
function exportAsPNG() {
  const canvas = canvasRef.value
  if (!canvas) return
  
  const link = document.createElement('a')
  link.download = 'drawing.png'
  link.href = canvas.toDataURL('image/png')
  link.click()
}

function exportAsJPEG() {
  const canvas = canvasRef.value
  if (!canvas) return
  
  const link = document.createElement('a')
  link.download = 'drawing.jpg'
  link.href = canvas.toDataURL('image/jpeg', 0.8)
  link.click()
}
</script>

<style scoped>
.drawing-test-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.connection-test {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.connection-test h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 1.2rem;
}

.connection-status {
  margin-bottom: 15px;
  font-size: 14px;
}

.connection-status span:last-child {
  font-weight: 600;
  color: #ff4d4f;
}

.connection-status span.connected {
  color: #52c41a;
}

.connection-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.page-header {
  text-align: center;
  color: white;
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0 0 10px 0;
  font-size: 36px;
  font-weight: 700;
}

.page-header p {
  margin: 0;
  font-size: 18px;
  opacity: 0.9;
}

.main-content {
  display: flex;
  gap: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.left-panel {
  flex-shrink: 0;
}

.center-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.canvas-container {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.test-canvas {
  border: 2px solid #ddd;
  border-radius: 8px;
  cursor: crosshair;
  touch-action: none;
}

.canvas-info {
  margin-top: 15px;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  font-size: 14px;
}

.info-item .value {
  font-weight: 600;
  color: #2196f3;
}

.color-preview {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 2px solid #ddd;
}

.right-panel {
  flex-shrink: 0;
  width: 300px;
}

.control-panel {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  height: fit-content;
}

.control-panel h3 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 20px;
  font-weight: 600;
  text-align: center;
  border-bottom: 2px solid #f0f0f0;
  padding-bottom: 15px;
}

.control-section {
  margin-bottom: 25px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.control-section h4 {
  margin: 0 0 15px 0;
  color: #555;
  font-size: 16px;
  font-weight: 600;
}

.setting-item {
  margin-bottom: 15px;
}

.setting-item label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.history-info p {
  margin: 5px 0;
  font-size: 14px;
  color: #666;
}

.history-actions,
.export-actions,
.test-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.history-actions .el-button,
.export-actions .el-button,
.test-actions .el-button {
  width: 100%;
}

.status-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 10px 20px;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.status-item {
  display: flex;
  gap: 10px;
  align-items: center;
}

.status-item .value {
  font-weight: 600;
  color: #4caf50;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content {
    flex-direction: column;
    align-items: center;
  }
  
  .left-panel,
  .right-panel {
    width: 100%;
    max-width: 400px;
  }
}

@media (max-width: 768px) {
  .drawing-test-page {
    padding: 10px;
  }
  
  .page-header h1 {
    font-size: 28px;
  }
  
  .page-header p {
    font-size: 16px;
  }
  
  .canvas-container {
    padding: 10px;
  }
  
  .test-canvas {
    max-width: 100%;
    height: auto;
  }
}
</style>
